package com.yc.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class MyJackJsonConfig {

    @Value("${spring.jackson.date-format}")
    private String pattern;
    @Value("${spring.jackson.time-zone}")
    private String timeZone;

    /**
     * 定义日期时间格式.
     */
    @Bean
    public DateTimeFormatter dateTimeFormatter() {
        return DateTimeFormatter.ofPattern(pattern);
    }


    @Bean
    public DateTimeFormatter dateFormatter() {
        int begin = pattern.indexOf("y");
        int end = pattern.lastIndexOf("d");
        String dateFormatter = pattern.substring(begin, end + 1);
        return DateTimeFormatter.ofPattern(dateFormatter);
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.timeZone(timeZone);

            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter()));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter()));

            builder.serializerByType(LocalDate.class, new LocalDateSerializer(dateFormatter()));
            builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(dateFormatter()));
        };
    }
//
//    @Bean
//    public Converter<String, LocalDateTime> localDateTimeConvert() {
//        return source -> LocalDateTime.parse(source, dateTimeFormatter());
//    }
//
//    /**
//     * 为RequestParameter配置日期格式转换器.
//     */
//    @Bean
//    public Converter<String, LocalDate> localDateConvert() {
//        return source -> LocalDate.parse(source, dateFormatter());
//    }
}
